package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.business.rule.FormDataActiveRuleByUpdateBatchHelp;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.BatchEditHelp;
import com.xbongbong.paas.help.BusinessUserTeamHelp;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.paas.help.FormDataValidateDataHelp;
import com.xbongbong.paas.help.FormExplainHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.ProSaveHelp;
import com.xbongbong.paas.help.SharePermissionHelp;
import com.xbongbong.paas.help.WorkflowHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.model.PaasProcessTemplateModel;
import com.xbongbong.paas.pojo.AttrValuePojo;
import com.xbongbong.paas.pojo.FormExplainPojo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.dto.FormDataUpdateBatchDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.vo.FormDataUpdateBatchVO;
import com.xbongbong.paas.service.workflow.trigger.impl.WorkflowFormDataOperationServiceImpl;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.paas.util.TitleUtil;
import com.xbongbong.parent.abstracts.AbstractBusinessBatchEditService;
import com.xbongbong.parent.help.CommonPermissionHelp;
import com.xbongbong.parent.pojo.BatchEditValidateReturnPoJo;
import com.xbongbong.parent.util.LogUtil;
import com.xbongbong.pro.businessrule.pojo.dto.ActiveRuleByUpdateBatchDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.EditFieldTypeEnum;
import com.xbongbong.pro.enums.PackageStatusEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.UserTeamErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.permission.pojo.dto.VerifyUpdatePermissionDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.domain.entity.ShareRuleEntity;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.PaasFormDataModel;
import com.xbongbong.saas.service.toolbox.help.PackageStatusHelp;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.sys.help.ProPermissionHelp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 吴峰
 * @date 2022/11/17 14:22
 */
@Service("paasBatchEditService")
@Slf4j
public class PaasBatchEditService extends AbstractBusinessBatchEditService<PaasFormEntityExt, PaasFormDataEntityExt> {

    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private FormDataValidateDataHelp formDataValidateDataHelp;
    @Resource
    private BatchEditHelp batchEditHelp;
    @Resource
    private WorkflowHelp workflowHelp;
    @Resource
    private PaasProcessTemplateModel paasProcessTemplateModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private PaasFormDataModel paasFormDataModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private PackageStatusHelp packageStatusHelp;
    @Resource
    private FormDataActiveRuleByUpdateBatchHelp formDataActiveRuleByUpdateBatchHelp;
    @Resource
    private WorkflowFormDataOperationServiceImpl workflowFormDataOperationService;
    @Resource
    private ProPermissionHelp proPermissionHelp;
    @Resource
    private SharePermissionHelp sharePermissionHelp;
    @Resource
    private BusinessUserTeamHelp businessUserTeamHelp;
    @Resource
    private CommonPermissionHelp commonPermissionHelp;
    @Resource
    private FormDataHelp formDataHelp;
    @Resource
    private FormExplainHelp formExplainHelp;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.PAAS.getCode());
    }


    @Override
    public List<PaasFormDataEntityExt> dataListAndSubDataList(FormDataUpdateBatchDTO formDataUpdateBatchDTO) throws XbbException {
        return paasEsModel.dataListAndSubDataList(formDataUpdateBatchDTO.getCorpid(), formDataUpdateBatchDTO.getSaasMark(), formDataUpdateBatchDTO.getBusinessType(), formDataUpdateBatchDTO.getFormId(), formDataUpdateBatchDTO.getDataIdList(), IndexTypeEnum.IDX_FORM_DATA);
    }

    @Override
    public List<FieldAttrEntity> getExplainList(FormDataUpdateBatchDTO formDataUpdateBatchDTO, List<PaasFormDataEntityExt> dataList) throws XbbException {
        PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(formDataUpdateBatchDTO.getCorpid(), formDataUpdateBatchDTO.getFormId(), formDataUpdateBatchDTO.getBusinessType());


        return JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
    }

    @Override
    public PaasFormEntityExt getFormEntity(FormDataUpdateBatchDTO formDataUpdateBatchDTO, List<PaasFormDataEntityExt> dataList) throws XbbException {
        return proFormHelp.getPaasFormExt(formDataUpdateBatchDTO.getFormId(), formDataUpdateBatchDTO.getBusinessType(), formDataUpdateBatchDTO.getCorpid());
    }

    @Override
    public BatchEditValidateReturnPoJo validateData(FormDataUpdateBatchDTO formDataUpdateBatchDTO, List<FieldAttrEntity> explainList, List<PaasFormDataEntityExt> dataList) throws XbbException {
        List<AttrValuePojo> fieldEditedList = formDataUpdateBatchDTO.getFieldEditedList();
        UserVO loginUser = formDataUpdateBatchDTO.getLoginUser();
        String corpid = formDataUpdateBatchDTO.getCorpid();
        Integer businessType = formDataUpdateBatchDTO.getBusinessType();
        List<Long> dataIdList = formDataUpdateBatchDTO.getDataIdList();
        Map<String,Object> editedAttr2ValueMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String,Object>  dummyAttr2ValueMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<String> attrList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (AttrValuePojo attrValuePojo : fieldEditedList) {
            String attr = attrValuePojo.getAttr();
            Object value = attrValuePojo.getValue();
            editedAttr2ValueMap.put(attr, value);
            Object dummyValue = CloneUtil.deepClone(value);
            dummyAttr2ValueMap.put(attr,dummyValue);
            attrList.add(attr);
        }

        Map<String, FieldAttrEntity> editedFieldExplainMap = ExplainUtil.getExplainMapByAttrList(explainList, attrList);

        filterValue4UpdateBatch(editedAttr2ValueMap, editedFieldExplainMap);
        formDataUpdateBatchDTO.judgeIsFieldDependence(editedFieldExplainMap);
        // 校验不可重复的单条数据
        for (String attr : editedAttr2ValueMap.keySet()) {
            FieldAttrEntity fieldAttrEntity = editedFieldExplainMap.get(attr);
            if (Objects.isNull(fieldAttrEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            if (Objects.equals(1, fieldAttrEntity.getNoRepeat()) && dataIdList.size() > 1) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.THE_FIELD_NOT_EDIT_BATCH);
            }
        }
        // 校验单条或多条数据的 提交格式
        for (Long dataId : dataIdList) {
            ValidateDataDTO validateDataDTO = new ValidateDataDTO();
            BeanUtil.copyProperties(formDataUpdateBatchDTO, validateDataDTO);
            JSONObject data = new JSONObject();
            for (Map.Entry<String, Object> av : editedAttr2ValueMap.entrySet()) {
                data.put(av.getKey(), av.getValue());
            }
            validateDataDTO.setData(data);
            validateDataDTO.setDataId(dataId);
            validateDataDTO.setExplainMap(editedFieldExplainMap);
            formDataValidateDataHelp.validateData(validateDataDTO);
        }
        // 是否有编辑权限，需要对每条数据进行
        // 字段可见可编辑和高级可见可编辑的判断--字段级别的校验
        batchEditHelp.checkEditPermission(new ArrayList<>(editedFieldExplainMap.values()), formDataUpdateBatchDTO, dataList);
        if (commonHelp.isOpenWorkFlow(corpid)) {
            boolean editAfterFinished = workflowHelp.getEditAfterFinished(corpid, formDataUpdateBatchDTO.getFormId(), businessType, formDataUpdateBatchDTO.getSaasMark(), loginUser);
            // 审批后能否编辑
            paasProcessTemplateModel.checkEditAfterFinished(editAfterFinished, dataList);
        } else {
            // 审批通过后是否允许编辑
            boolean editAfterFinished = paasProcessTemplateModel.getEditAfterFinished(formDataUpdateBatchDTO.getAppId(),formDataUpdateBatchDTO.getMenuId(),formDataUpdateBatchDTO.getFormId(), loginUser);
            // 审批后能否编辑
            paasProcessTemplateModel.checkEditAfterFinished(editAfterFinished, dataList);
        }

        // 设置修改后的数据以及 LogValue (解析不同的数据结构)
        setBatchEditDataAndLog(editedAttr2ValueMap, dummyAttr2ValueMap, editedFieldExplainMap, formDataUpdateBatchDTO);
        return new BatchEditValidateReturnPoJo(editedFieldExplainMap, editedAttr2ValueMap, dummyAttr2ValueMap);
    }

    @Override
    public FormDataUpdateBatchVO batchEditAttr(FormDataUpdateBatchDTO formDataUpdateBatchDTO, BatchEditValidateReturnPoJo batchEditValidateReturnPoJo, List<PaasFormDataEntityExt> dataList, PaasFormEntityExt formEntity, List<FieldAttrEntity> list) throws XbbException {
        updateBatch(formDataUpdateBatchDTO, formEntity, ExplainUtil.getExplainMapByList(list, null));
        return new FormDataUpdateBatchVO();
    }

    @Override
    public void checkDataEditPermission(FormDataUpdateBatchDTO formDataUpdateBatchDTO, PaasFormEntityExt formEntity, List<PaasFormDataEntityExt> formDataList) throws XbbException{

        String corpid = formDataUpdateBatchDTO.getCorpid();
        Long formId = formDataUpdateBatchDTO.getFormId();
        UserVO loginUser = formDataUpdateBatchDTO.getLoginUser();
        List<Long> dataIdList = formDataUpdateBatchDTO.getDataIdList();
        Integer businessType = formDataUpdateBatchDTO.getBusinessType();
        Integer saasMark = formDataUpdateBatchDTO.getSaasMark();
        Long menuId = formDataUpdateBatchDTO.getMenuId();
        FormExplainPojo formAndExplain = formExplainHelp.getFormAndExplain(corpid, businessType, formId);
        Map<Long, List<String>> ownerIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        businessUserTeamHelp.getUserIdMapSetShow(new HashSet<>(), dataIdList, corpid, businessType, false, ownerIdMap, coUserIdMap, DelEnum.NORMAL.getDel());
        if (Objects.equals(formDataUpdateBatchDTO.getIsBatch(), BasicConstant.ZERO) || Objects.equals(formDataUpdateBatchDTO.getIsBatch(), BasicConstant.TWO)){
            PaasFormDataEntityExt paasFormDataEntityExt = formDataHelp.getFormData(corpid, saasMark, businessType, dataIdList.get(0));
            FormDataDetailDTO formDataDetailDTO = new FormDataDetailDTO(dataIdList.get(0), saasMark, businessType, menuId, paasFormDataEntityExt.getCreatorId(), loginUser);
            paasFormDataEntityExt.getData().put(FieldTypeEnum.OWNERID.getAlias(), ownerIdMap.get(paasFormDataEntityExt.getId()));
            paasFormDataEntityExt.getData().put(FieldTypeEnum.COUSERID.getAlias(), coUserIdMap.get(paasFormDataEntityExt.getId()));
            VerifyUpdatePermissionDTO verifyUpdatePermissionDTO = new VerifyUpdatePermissionDTO(loginUser, paasFormDataEntityExt);
            boolean hasDataPermission = commonPermissionHelp.checkEditPermission(formDataDetailDTO, verifyUpdatePermissionDTO, ExplainUtil.getExplainMapByList(formAndExplain.getExplainList()));
            if (!hasDataPermission){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050.getCode(), String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), OperateTypeEnum.EDIT.getName()));
            }
        }else{
        //获取该用户在改表单下的共享规则
        List<ShareRuleEntity> ruleEntities = sharePermissionHelp.getRuleEntities(corpid, formId, loginUser.getUserId());
        List<Long> errorDataIdList = new ArrayList<>();
        for (PaasFormDataEntityExt paasFormDataEntityExt : formDataList) {
            paasFormDataEntityExt.getData().put(FieldTypeEnum.OWNERID.getAlias(), ownerIdMap.get(paasFormDataEntityExt.getId()));
            paasFormDataEntityExt.getData().put(FieldTypeEnum.COUSERID.getAlias(), coUserIdMap.get(paasFormDataEntityExt.getId()));
            VerifyUpdatePermissionDTO verifyUpdatePermissionDTO = new VerifyUpdatePermissionDTO(loginUser, paasFormDataEntityExt);
            verifyUpdatePermissionDTO.setRuleEntities(ruleEntities);
            FormDataDetailDTO formDataDetailDTO = new FormDataDetailDTO(paasFormDataEntityExt.getId(), saasMark, businessType, menuId, paasFormDataEntityExt.getCreatorId(), loginUser);
            boolean hasDataPermission = commonPermissionHelp.checkEditPermission(formDataDetailDTO, verifyUpdatePermissionDTO, ExplainUtil.getExplainMapByList(formAndExplain.getExplainList()));
            if (!hasDataPermission){
                errorDataIdList.add(paasFormDataEntityExt.getId());
            }
        }
        //无权限操作的数据直接移除，后面优化再做批量报错的封装
        if(CollectionUtils.isNotEmpty(errorDataIdList)){
            formDataList.removeIf(v -> errorDataIdList.contains(v.getId()));
            dataIdList.removeIf(errorDataIdList :: contains);
        }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    public void updateBatch(FormDataUpdateBatchDTO formDataUpdateBatchDTO, PaasFormEntityExt paasFormEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        Integer fieldType = formDataUpdateBatchDTO.getFieldType();
        String corpid = formDataUpdateBatchDTO.getCorpid();
        try {
            if (Objects.isNull(EditFieldTypeEnum.getByType(fieldType))) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EDIT);
            }
            Map<String, Object> map = BeanUtil.convertBean2Map(formDataUpdateBatchDTO, true);
            map.put("ids", formDataUpdateBatchDTO.getDataIdList());
            List<PaasFormDataEntityExt> list = paasFormDataModel.findEntitys(map);
            if (list == null || list.size() != formDataUpdateBatchDTO.getDataIdList().size()) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            //团队权限校验前置了
            //validateTeamMembersCheckEditPermission(formDataUpdateBatchDTO, paasFormEntityExt, explainMap, list);

            List<UpdateDataEntity> jsonObjectList = new ArrayList<>();
            for (PaasFormDataEntityExt formData: list) {
                JSONObject data = ProSaveHelp.getBatchUpdateData(formDataUpdateBatchDTO.getFieldEditedList());
                UpdateDataEntity updateDataEntity = ExplainUtil.getUpdateData(formData.getId(), data, corpid);
                jsonObjectList.add(updateDataEntity);
            }
            paasFormDataModel.updateBatch(jsonObjectList, corpid);

            // paas表单批量编辑日志
            // 表单标题名称
            Map<String, Object> newMap = BeanUtil.convertBean2Map(formDataUpdateBatchDTO, true);
            newMap.put("ids", formDataUpdateBatchDTO.getDataIdList());
            newMap.put("del", 0);
            List<PaasFormDataEntityExt> newList = paasFormDataModel.findEntitys(map);
            List<Long> dataIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<String> titleList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

            List<FieldAttrEntity> fieldAttrEntityList = formDataUpdateBatchDTO.getFieldEditedList().stream().
                    map(attrValuePojo -> explainMap.get(attrValuePojo.getAttr())).collect(Collectors.toList());
            for (PaasFormDataEntityExt paasFormDataEntityExt: newList) {
                dataIdList.add(paasFormDataEntityExt.getId());
                JSONObject data = paasFormDataEntityExt.getData();
                List<FormTitlePoJo> formTitleList = ExplainUtil.getFormTitle(JSONArray.parseArray(paasFormEntityExt.getCustomTitle()), explainMap, data, fieldAttrEntityList, paasFormDataEntityExt);
                String title = "--";
                if(!formTitleList.isEmpty()){
                    List<Object> value = formTitleList.get(0).getValue();
                    title = value.isEmpty() ? title : value.get(0).toString();
                }
                titleList.add(title);
            }
            String updataItem = StringUtils.join(titleList, "，");
            String userId = formDataUpdateBatchDTO.getUserId();
            String loginUserName = formDataUpdateBatchDTO.getLoginUserName();
            String formName = paasFormEntityExt.getName();

            String changedLogItemsStr = LogUtil.getChangedLogItemsStr(formDataUpdateBatchDTO.getLogFieldEditedList());
            //数量大于1条时
            if(dataIdList.size() > 1 ){
                //用户“%s”批量编辑了“%s”数据：%s，合计： %s 条数据更新成功，具体操作数据见详情
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_BATCH_ATTR), loginUserName, formName,
                        changedLogItemsStr, dataIdList.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(formName);
                infoArrPojo.setContent(updataItem);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.PAAS_FORM_DATA, OperateTypeEnum.EDIT,
                        "", "", memo, formDataUpdateBatchDTO.getHttpHeader());
            } else if (Objects.equals(dataIdList.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_ATTR), loginUserName, formName, updataItem,
                        changedLogItemsStr);
                mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.PAAS_FORM_DATA, OperateTypeEnum.EDIT,
                        dataIdList.get(0).toString(), updataItem, memo, formDataUpdateBatchDTO.getHttpHeader());
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            log.error("proFormDataService.updateBatch 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 校验是否有 无权限编辑者编辑了数据
     * @param formDataUpdateBatchDTO
     * @param paasFormEntityExt
     * @param explainMap
     * @param list
     * @throws XbbException
     */
    public void validateTeamMembersCheckEditPermission(FormDataUpdateBatchDTO formDataUpdateBatchDTO, PaasFormEntityExt paasFormEntityExt, Map<String, FieldAttrEntity> explainMap, List<PaasFormDataEntityExt> list) throws XbbException {
        List<String> errorNameList = new ArrayList<>();
        List<Long> errorIdList = userTeamHelp.batchTeamMembersCheckEditPermission(formDataUpdateBatchDTO.getBusinessType(), formDataUpdateBatchDTO.getSaasMark(),
                formDataUpdateBatchDTO.getMenuId(), formDataUpdateBatchDTO.getLoginUser(), formDataUpdateBatchDTO.getDistributorMark(),
                formDataUpdateBatchDTO.getDataIdList(), explainMap);
        for (PaasFormDataEntityExt paasFormDataEntityExt : list) {
            if (errorIdList.contains(paasFormDataEntityExt.getDataId())) {
                List<FormTitlePoJo> formTitleList = ExplainUtil.getFormTitle(JSONArray.parseArray(paasFormEntityExt.getCustomTitle()), explainMap, paasFormDataEntityExt.getData(), new ArrayList<>(explainMap.values()), paasFormDataEntityExt);
                String errorName = null;
                if (!formTitleList.isEmpty()) {
                    formTitleList.forEach(titlePoJo -> {
                        FieldAttrEntity fieldAttrEntitySen = explainMap.get(titlePoJo.getAttr());
                        if (Objects.nonNull(fieldAttrEntitySen) && ExplainUtil.isCombo(fieldAttrEntitySen.getFieldType())) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put(titlePoJo.getAttr(), titlePoJo.getValue());
                            Object value = ItemUtil.analysisComboReturnStr(jsonObject, fieldAttrEntitySen);
                            titlePoJo.setValue(Collections.singletonList(value));
                        }
                    });
                    errorName = TitleUtil.getTitle(formTitleList);
                }
                if (StringUtil.isEmpty(errorName)) {
                    errorName = "--";
                }
                errorNameList.add(errorName);
            }
        }
        String nameStr = org.apache.commons.lang.StringUtils.join(errorNameList, "、");
        if (CollectionUtils.isNotEmpty(errorNameList)) {
            throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_271038.getCode(), String.format(UserTeamErrorCodeEnum.API_ERROR_271038.getMsg(), nameStr));
        }
    }

    @Override
    public void after(FormDataUpdateBatchDTO formDataUpdateBatchDTO, List<PaasFormDataEntityExt> list, PaasFormEntityExt formEntityExt) throws XbbException {
        String businessRules = formEntityExt.getBusinessRules();
        if (isEnableNewWorkflow(formDataUpdateBatchDTO, list)) {
            // 业务规则逻辑 start
            startActiveRule(businessRules, formDataUpdateBatchDTO, list);
        }

        // 业务规则逻辑 start
        startActiveRule(businessRules, formDataUpdateBatchDTO, list);
    }

    private void startActiveRule(String businessRules, FormDataUpdateBatchDTO formDataUpdateBatchDTO, List<PaasFormDataEntityExt> list) throws XbbException{
        // 业务规则逻辑 start
        if(Objects.equals("1", businessRules)){

            ActiveRuleByUpdateBatchDTO activeRuleByUpdateBatchDTO = new ActiveRuleByUpdateBatchDTO();
            BeanUtil.copyProperties(formDataUpdateBatchDTO, activeRuleByUpdateBatchDTO);
            activeRuleByUpdateBatchDTO.setFormDataIdList(formDataUpdateBatchDTO.getDataIdList());
            activeRuleByUpdateBatchDTO.setEditFlag(1);
            activeRuleByUpdateBatchDTO.setOldDataList(list);
            formDataActiveRuleByUpdateBatchHelp.activeRuleByUpdateBatch(activeRuleByUpdateBatchDTO);
        }
    }

    /**
     * 是否启用新工作流
     * 且判断是否符合触发类型
     * @param formDataUpdateBatchDTO
     * @return
     * @throws XbbException
     */
    private boolean isEnableNewWorkflow(FormDataUpdateBatchDTO formDataUpdateBatchDTO, List<PaasFormDataEntityExt> oldDataList) throws XbbException {
        if (!commonHelp.isOpenWorkFlow(formDataUpdateBatchDTO.getCorpid())) {
            return false;
        }
        // 套餐限制
        Integer allStatus = packageStatusHelp.getPackageStatus(formDataUpdateBatchDTO.getCorpid(), ValueAddedTypeEnum.WORKFLOW, formDataUpdateBatchDTO.getDataIdList().size());
        if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode())) {
            return true;
        }
        //是不是要循环发送
        workflowFormDataOperationService.workflowUpdateBatchTrigger(formDataUpdateBatchDTO, oldDataList);
        return true;
    }
}
